package com.siqi.hr.common.exportexcel;

import com.siqi.hr.system.custom.exception.ExcelException;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Calendar;

public class ExportExcel2003 implements ExportExcel {
	private static String DATE_FORMAT = "yyyy-mm-dd HH:mm:ss";

	private static String NUMBER_FORMAT = " #,##0.00 ";
	private String xlsFileName;
	private HSSFWorkbook workbook;
	private HSSFSheet sheet;
	private HSSFRow row;

	public ExportExcel2003(String fileName) {
		this.xlsFileName = fileName;
		this.workbook = new HSSFWorkbook();
		this.sheet = this.workbook.createSheet();
	}

	public void export() throws ExcelException {
		try {
			FileOutputStream fOut = new FileOutputStream(this.xlsFileName);
			this.workbook.write(fOut);
			fOut.flush();
			fOut.close();
		} catch (FileNotFoundException e) {
			throw new ExcelException("生成导出Excel文件出错!", e);
		} catch (IOException e) {
			throw new ExcelException("写入Excel文件出错!", e);
		}
	}

	public void createRow(int index) {
		this.row = this.sheet.createRow(index);
	}

	public void setCell(int index, String value) {
		HSSFCell cell = this.row.createCell(index);
		cell.setCellType(1);
		cell.setCellValue(value);
		HSSFCellStyle cellStyle = configExcelStyle(this.workbook);
		cell.setCellStyle(cellStyle);
	}

	public void setCell(int index, Calendar value) {
		HSSFCell cell = this.row.createCell(index);
		cell.setCellValue(value.getTime());
		HSSFCellStyle cellStyle = configExcelStyle(this.workbook);
		cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(DATE_FORMAT));
		cell.setCellStyle(cellStyle);
	}

	public void setCell(int index, int value) {
		HSSFCell cell = this.row.createCell(index);
		cell.setCellType(0);
		cell.setCellValue(value);
		HSSFCellStyle cellStyle = configExcelStyle(this.workbook);
		cell.setCellStyle(cellStyle);
	}

	public void setCell(int index, double value) {
		HSSFCell cell = this.row.createCell(index);
		cell.setCellType(0);
		cell.setCellValue(value);
		HSSFCellStyle cellStyle = configExcelStyle(this.workbook);
		HSSFDataFormat format = this.workbook.createDataFormat();
		cellStyle.setDataFormat(format.getFormat(NUMBER_FORMAT));
		cell.setCellStyle(cellStyle);
	}

	public void setCell(int index, boolean value) {
	}

	public void setCell(int index, Timestamp value) {
		HSSFCell cell = this.row.createCell(index);
		cell.setCellValue(value.getTime());
		HSSFCellStyle cellStyle = configExcelStyle(this.workbook);
		cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(DATE_FORMAT));
		cell.setCellStyle(cellStyle);
	}

	public HSSFCellStyle configExcelStyle(Workbook wb) {
		HSSFCellStyle style = (HSSFCellStyle) wb.createCellStyle();
		HSSFDataFormat format = (HSSFDataFormat) wb.createDataFormat();
		style.setDataFormat(format.getFormat("@"));
		return style;
	}
}
